package com.hup.timer.service.gesture;

import com.hup.timer.constant.TimerConstant;
import com.hup.timer.service.gesture.TimerWindowGesture.GestureCallback;
import com.hup.utils.commons.hardware.ScreenUtil;
import lombok.extern.log4j.Log4j2;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @author hugan
 * @date 2020/4/6
 */
@Log4j2
public class MoveFrameListener extends MouseAdapter {

    /**
     * 磁性边距
     */
    private static final int EDGE_PX = TimerConstant.EDGE_PX;

    private final Window win;
    private final GestureCallback callback;
    private Insets sc;
    /**
     * 窗口是否被拖拽过
     */
    private boolean hadMoved;
    /**
     * 鼠标拖拽前的坐标
     */
    private int mX0, mY0;
    /**
     * 窗口拖拽前的坐标
     */
    private int wX0, wY0;

    public MoveFrameListener(GestureCallback callback) {
        this.win = callback.getWindow();
        this.callback = callback;
    }

    @Override
    public void mousePressed(MouseEvent e) {
        sc = ScreenUtil.getScreenUsableCoor();
        mX0 = e.getXOnScreen();
        mY0 = e.getYOnScreen();
        log.info("激活移动窗口, mX0={}, mY0={}", mX0, mY0);
        wX0 = win.getX();
        wY0 = win.getY();
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        int xDiff = e.getXOnScreen() - mX0;
        int yDiff = e.getYOnScreen() - mY0;

        int x = wX0 + xDiff;
        int y = wY0 + yDiff;
        int winWid = win.getWidth();
        int winHei = win.getHeight();

        boolean atEdge = false;
        if (x < sc.left + EDGE_PX) {
            atEdge = true;
            x = sc.left;
        } else if (x + winWid > sc.right - EDGE_PX) {
            atEdge = true;
            x = sc.right - winWid;
        }
        if (y < sc.top + EDGE_PX) {
            atEdge = true;
            y = sc.top;
        } else if (y + winHei > sc.bottom - EDGE_PX) {
            atEdge = true;
            y = sc.bottom - winHei;
        }

        win.setLocation(x, y);
        hadMoved = true;
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        if (hadMoved) {
            callback.afterMoved();
            hadMoved = false;
        }
    }
}
